<?php

namespace Biz\service\course;

use Biz\cache\course\WhiteUser;
use Biz\model\course\Chapter as mChapter;
use Biz\model\course\Course as mCourse;
use Biz\model\course\CourseEvaluation as mCourseEvaluation;
use Biz\model\course\CourseExtend as mCourseExtend;
use Biz\model\course\CourseOrder as mCourseOrder;
use Biz\model\course\CourseWhiteUser;
use Biz\service\Share;
use Biz\tools\BizUrl;
use Doraemon\cache\Queue;
use Doraemon\pockets\constInterface\LinkConf;
use Doraemon\service\User;
use Doraemon\service\Videos\Videos;
use Doraemon\tools\HhzClient;
use Doraemon\tools\HhzEnv;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\LinkFormat;


class Course
{

    /**
     * 课程列表
     * @param int $page
     * @param int $pageSize
     * @param int $active_uid
     * @return array
     */
    public static function getList($page = 1, $pageSize = 20, $active_uid = 0)
    {
        $page = $page ? $page : 1;
        $limit = [($page - 1) * $pageSize, $pageSize];
        $where = [
            'course_status' => mCourse::STATUS_ONLINE,
            'is_show' => 1,
            'LIMIT' => $limit,
            'ORDER' => ['sort' => 'ASC', 'course_id' => 'ASC'],
        ];
        if (HhzEnv::isGray()) {//gray 环境公开，不公开，不受限制
            unset($where['is_show']);
        }
        $result = mCourse::selectByWhere($where);
        $course_orders = [];
        if ($result && is_array($result) && $active_uid) {
            $course_ids = array_column($result, 'course_id');
            $course_orders = mCourseOrder::selectByWhere(['course_id' => $course_ids, 'uid' => $active_uid, 'order_status' => mCourseOrder::STATUS_SUCCESS]);
            if ($course_orders && is_array($course_orders)) {
                $course_orders = array_combine(array_column($course_orders, 'course_id'), $course_orders);
            }
        }
        unset($where['LIMIT']);
        unset($where['ORDER']);
        $count = mCourse::selectCount($where);
        $isOver = (($page * $pageSize) >= $count) ? 1 : 0;
        $list = [];
        foreach ($result as $row) {
            $course_info = self::formatInfoForCourseList($row);
            $course_info['is_owner'] = ($course_orders && $course_orders[$row['course_id']]) ? 1 : 0;
            $list[] = $course_info;
        }
        return ['list' => $list, 'is_over' => $isOver];
    }

    /**
     * 获取课程信息
     * @param $courseIds
     * @return array
     */
    public static function getListByIds($courseIds)
    {
        $where = [
            'course_id' => $courseIds,
            'course_status' => mCourse::STATUS_ONLINE,
        ];
        $result = mCourse::selectByWhere($where);
        $list = [];
        foreach ($result as $row) {
            $list[$row['course_id']] = self::formatInfoForCourseList($row);
        }
        return $list;
    }

    /**
     * 我的课程列表
     * @param $uid
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public static function getMyCourseList($uid, $page = 1, $pageSize = 20)
    {
        $limit = [($page - 1) * $pageSize, $pageSize];
        $where = [
            'uid' => $uid,
            'order_status' => mCourseOrder::STATUS_SUCCESS,
            'LIMIT' => $limit,
            'ORDER' => ['addtime' => 'DESC'],
        ];
        $result = mCourseOrder::selectByWhere($where, ['course_id', 'uid']);
        $courseIds = array_column($result, 'course_id');
        unset($where['LIMIT']);
        unset($where['ORDER']);
        $count = mCourseOrder::selectCount($where);
        $isOver = (($page * $pageSize) >= $count) ? 1 : 0;
        $list = [];
        if ($courseIds) {
            $result = mCourse::selectByWhere(['course_id' => $courseIds]);
            $courseList = [];
            foreach ($result as $row) {
                $courseList[$row['course_id']] = self::formatInfoForCourseList($row, 1);
            }
            foreach ($courseIds as $courseId) {
                if (isset($courseList[$courseId])) {
                    $list[] = $courseList[$courseId];
                }
            }
        }
        return ['list' => $list, 'is_over' => $isOver];
    }

    /**
     * 课程详情
     * @param $courseId
     * @param int $uid
     * @return array
     */
    public static function getDetail($courseId, $uid = 0)
    {
        $result = [];
        $info = mCourse::getByWhere(['course_id' => $courseId]);
        if ($info) {
            $info['spec_img'] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $info['spec_img'], ImgUrl::IMAGE_SIZE_OP_ORI);
            $info['share_img'] = $info['share_img'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $info['share_img'], ImgUrl::IMAGE_SIZE_OP_ORI) : '';
            $info['teacher_img'] = $info['teacher_img'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $info['teacher_img'], ImgUrl::IMAGE_SIZE_OP_ORI) : '';
            $isEvaluatedArr = mCourseEvaluation::isEvaluated($courseId, $uid);
            $isEvaluated = $isEvaluatedArr[$courseId];
            $isOwner = self::isOwnerCourse($uid, $courseId);
            $chapterList = self::getChapterList($courseId, $uid, $isOwner);
            $result = [
                'course_id' => $courseId,
                'title' => $info['title'],
                'desc' => $info['desc'],
                'spec_img' => $info['spec_img'],
                'teacher_img' => $info['teacher_img'],
                'original_price' => floatval($info['original_price']) > 0 ? $info['original_price'] : '0.00',
                'price' => $info['price'],
                'chapter_num' => $info['chapter_num'],
                'duration' => $info['duration'],
                'is_try' => $info['is_try'],
                'is_evaluated' => $isEvaluated,
                'status' => $info['course_status'],
                'apple_gid' => $info['apple_gid'],
                'is_owner' => $isOwner,
                'share_info' => Share::getCourseShare($info),
                'h5_url' => Hhzurl::h5CourseIntroduce($courseId),
                'buy_help_url' => BizUrl::h5ActivityPage(409),
                'video_url' => '',
                'chapter_list' => $chapterList,
                'is_free' => $info['is_free'],
                'course_tag' => $info['course_tag'] ? explode(",", $info['course_tag']) : [],

            ];
        }
        return $result;
    }

    /**
     * 图文详情
     * @param $courseId
     * @return array
     */
    public static function getDetailContent($courseId)
    {
        $info = mCourseExtend::getByWhere(['course_id' => $courseId]);
        $content = [];
        if ($info && $info['content']) {
            $contentList = explode(',', $info['content']);
            foreach ($contentList as $row) {
                if ($row) {
                    $content[] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $row, ImgUrl::IMAGE_SIZE_OP_ORI);
                }
            }
        }
        return $content;
    }

    /**
     * 章节列表
     * @param $courseId
     * @param $uid
     * @param $isOwner
     * @return array|bool
     */
    public static function getChapterList($courseId, $uid, $isOwner)
    {
        $result = mChapter::selectByWhere(['course_id' => $courseId, 'chapter_status' => mChapter::STATUS_NORMAL, 'ORDER' => ['sort' => 'ASC', 'id' => 'ASC']]);
        $list = [];
        $videoIds = array_column($result, 'video_id');
        $videoIds = array_filter($videoIds);
        $videoList = Videos::getCanUseVideoInfosByIds($videoIds, Videos::VIDEO_DEFINITION_OD);
        $i = 1;
        foreach ($result as $row) {
            $videoInfo = isset($videoList[$row['video_id']]) ? $videoList[$row['video_id']] : [];
            $videoUrl = ($isOwner && $videoInfo) ? $videoInfo['play_url'] : '';
            $picUrl = $videoInfo ? $videoInfo['o_500_url'] : '';
            if ($isOwner && version_compare(HhzClient::getClientVersion(), '4.7.0', "<")) {
                $picUrl = 'https://img.haohaozhu.cn/Op-imageShow/4103820qo0f00UA00qa26uh?iv=1';
            }
            $sort = str_pad($i, 2, '0', STR_PAD_LEFT);
            $list[] = [
                'id' => $row['id'],
                'course_id' => $row['course_id'],
                'name' => $row['name'],
                'video_url' => $videoUrl,
                'video_id' => $row['video_id'],
                'is_try' => $row['is_try'],
                'pic_url' => $picUrl,
                'sort' => $sort,
                'duration' => $row['duration'],
            ];
            $i++;
        }
        return $list;
    }

    /**
     * 课程列表格式化
     * @param $courseInfo
     * @param $isOwner
     * @return array
     */
    public static function formatInfoForCourseList($courseInfo, $isOwner = false)
    {
        $result = [
            'course_id' => $courseInfo['course_id'],
            'title' => $courseInfo['title'],
            'desc' => $courseInfo['desc'],
            'spec_img' => ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $courseInfo['spec_img'], ImgUrl::IMAGE_SIZE_OP_ORI),
            'original_price' => floatval($courseInfo['original_price']) > 0 ? $courseInfo['original_price'] : '0.00',
            'teacher_img' => ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $courseInfo['teacher_img'], ImgUrl::IMAGE_SIZE_OP_ORI),
            'price' => $courseInfo['price'],
            'chapter_num' => $courseInfo['chapter_num'],
            'duration' => $courseInfo['duration'],
            'is_try' => $courseInfo['is_try'],
            'status' => $courseInfo['course_status'],
            'is_free' => $courseInfo['is_free'],
            'course_tag' => $courseInfo['course_tag'] ? explode(",", $courseInfo['course_tag']) : []
        ];
        if ($isOwner) {
            $result['is_receive'] = $courseInfo['receive_link'] ? 1 : 0;
        }
        return $result;
    }

    /**
     * 评价
     * @param $uid
     * @param $courseId
     * @param $evaluteData
     * @return bool|int|mixed|string
     */
    public static function Evaluate($uid, $courseId, $evaluteData)
    {
        $result = false;
        $arr = mCourseEvaluation::isEvaluated($courseId, $uid);
        if (!$arr[$courseId]) {
            $data = [
                'uid' => $uid,
                'course_id' => $courseId,
                'course_start' => $evaluteData['course_start'],
                'teacher_start' => $evaluteData['teacher_start'],
                'ue_start' => $evaluteData['ue_start'],
                'content' => $evaluteData['content']
            ];
            $result = mCourseEvaluation::insertData($data);
        }
        return $result;
    }

    public static function getCourseInfo($courseId)
    {
        $info = [];
        if ($courseId) {
            $info = mCourse::getByWhere(['course_id' => $courseId, 'course_status' => mCourse::STATUS_ONLINE]);
        }
        return $info;
    }

    public static function getCourseInfoByAppleGid($appleGid)
    {
        $info = [];
        if ($appleGid) {
            $info = mCourse::getByWhere(['apple_gid' => $appleGid]);
        }
        return $info;
    }

    public static function isOwnerCourse($uid, $courseId)
    {
        $whiteUids = self::getWhiteUsers($courseId);//课程白名单
        if (in_array($uid, $whiteUids)) {
            $isOwner = 1;
        } else {
            $orderIds = mCourseOrder::selectByWhere(['uid' => $uid, 'course_id' => $courseId, 'order_status' => mCourseOrder::STATUS_SUCCESS], ['id']);
            $isOwner = $orderIds ? 1 : 0;
        }
        return $isOwner;
    }

    public static function getWhiteUsers($courseId)
    {
        $uids = [];
        if ($courseId) {
            $where = [
                'course_id' => $courseId,
                'white_state' => CourseWhiteUser::STATE_NORMAL,
                'expired_time[>]' => time()
            ];
            $uids = CourseWhiteUser::selectByWhere($where, 'uid');
            $whiteUids = WhiteUser::getWhiteUsers($courseId);//课程白名单
            $uids = array_merge($uids, $whiteUids);
            $uids = array_unique(array_filter($uids));
        }
        return $uids;
    }

    /**
     * 新用户成长活动获取课程
     * @param $uid uid
     * @param $courseId 课程id
     * @return false|int|mixed|string
     */
    public static function receiveCourseForUserGrowth($uid, $courseId)
    {
        $courseInfo = mCourse::getByWhere(['course_id' => $courseId]);
        if (empty($courseInfo)) {
            return false;
        }
        $expiredTime = strtotime(date('Y-m-d')) + (86400 * 180 + 86399);//180天有效
        $result = self::createWhiteUser($uid, $courseId, CourseWhiteUser::TYPE_ACTIVITY, '新用户成长，萌新7天礼', $expiredTime, 'user-growth');
        if ($result) {
            $linkArr = LinkFormat::generateLink(LinkConf::LINK_APP_COURSE_DETAIL, json_encode(['id' => $courseId]));
            $link = isset($linkArr['app_template']) ? $linkArr['app_template'] : '';
            $msgInfo = [
                'send_user' => User::HAOHAOZHUFULIGUAN_UID,
                'con_type' => 2,
                'content' => json_encode([
                    'title' => $courseInfo['title'],
                    'desc' => '180日内有效哦，请立即查看吧～',
                    'cover_img' => ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $courseInfo['spec_img'], ImgUrl::IMAGE_SIZE_OP_ORI),
                    'link' => $link,
                ])
            ];
            Queue::insertQueue('queue/im/send', [
                'to_uids' => [$uid],
                'msgInfo' => $msgInfo
            ], Queue::QUEUE_DORAEMON);
        }
        return $result;
    }

    public static function createWhiteUser($uid, $courseId, $type, $remark, $expiredTime = null, $identify = '', $adminId = 0)
    {
        if (empty($uid) || empty($type) || empty($courseId) || empty($remark)) {
            return false;
        }
        if (is_null($expiredTime)) {
            $expiredTime = strtotime('2039-01-01');
        }
        $data = [
            'uid' => $uid,
            'course_id' => $courseId,
            'expired_time' => $expiredTime,
            'type' => $type,
            'remark' => $remark,
            'identify' => $identify,
            'white_state' => CourseWhiteUser::STATE_NORMAL,
            'admin_id' => $adminId
        ];
        $result = CourseWhiteUser::insertData($data);
        return $result;
    }

    /**
     * 章节是否支持试看
     * @param $courseId 课程id
     * @param $chapterId 章节id
     * @return bool
     */
    public static function isTryVideo($courseId, $chapterId)
    {
        $info = mChapter::getByWhere(['id' => $chapterId, 'course_id' => $courseId, 'is_try' => 1, 'chapter_status' => mChapter::STATUS_NORMAL]);
        return $info ? true : false;
    }

}